package Sources;

import java.io.File;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import DataTags.DataTagsAdapter;
import DataTags.DataTagsToFiles;
import DataTags.files;
import Factory.SFac;
import Hiber.Manager;
import Main.main;

/**
 * @author Shinichi
 *
 */
public class SourcesDB implements Sources{

	DataTagsAdapter DTA=null;
	//Implementation for DB
	private int ID=1;
	@SuppressWarnings("unchecked")
	public void deleteSource(String what) {		
		SessionFactory sessionQFactory = SFac.get();
		Session session = sessionQFactory.openSession();
		Manager<sourcesdef> manager = new Manager<sourcesdef>(session);
		what=what.replace('\\', '_');
		String q0="SELECT s FROM sourcesdef s WHERE s.path LIKE '"+what+"%'";
		Query query0=session.createQuery(q0);
		List<sourcesdef> sourcesdefs=query0.list();
		int sid=sourcesdefs.get(0).getID();
		for (sourcesdef sourcesdef1 : sourcesdefs) {
			manager.delete(sourcesdef1);
		}
		//get all the expressions of this source and delete them
		String q1="SELECT e FROM expdef e WHERE e.sID='"+sid+"'";
		Query query1=session.createQuery(q1);
		Manager<expdef> expman=new Manager<expdef>(session);
		List<expdef> explist=query1.list();
		for (expdef expdef1 : explist) {
			expman.delete(expdef1);
			
		}
		session.flush();
		what=what.replace('\'', '@');
		String q="SELECT f FROM files f WHERE f.path LIKE '"+what+"%'";
		Query query=session.createQuery(q);
		List<files> files=query.list();
		what=what.replace('@', '\'');
		what=what.replace('_', '\\');
		if(DTA==null){
			DTA=main.menu.search.getDataTagsAdapter();
		}
		main.menu.log.update("Removing all source's files from DB");
		for (files files2 : files) {
			DTA.deleteFile(new File(files2.getPath()));
		}
		session.flush();
		session.close();
		//will make listener to stop listening to this source
		main.listener.undo(what);
	}

	/**
	 * Implementation for DB - Adding a new Source
	 * will check if the given path exists inside the system
	 * if not passes an exception back to the calling function
	 * if yes inserts it into the DB
	 */
	public void insertSource(String path,String[] exp) throws InvalidPathException {
			if((path.length()<3)||(path.charAt(1)!=':')||(path.charAt(2)!='\\')){
				throw new InvalidPathException(path, path);
			}
			Path a=Paths.get(path);
			SessionFactory sessionQFactory = SFac.get(); 
				//new Configuration().configure().buildSessionFactory();
			Session session = sessionQFactory.openSession();
			Manager<sourcesdef> manager = new Manager<sourcesdef>(session);
			sourcesdef newSource=new sourcesdef();	
			newSource.setID(ID);
			ID++;
			newSource.setPath(path);
			manager.save(newSource);
			//adding the expressions we got with the source
			Manager<expdef> expman=new Manager<expdef>(session);
			int sid=newSource.getID();
			for (String exp2 : exp) {
				expdef expression=new expdef();
				expression.setExp(exp2);
				expression.setsID(sid);
				expman.save(expression);
			}
			session.flush();
			File directory = new File(path);
			Index(directory);
	}
	/**
	 * Adds all the files inside the directory and in its sub directories into the DB
	 * @param dir
	 * @param manager
	 */
	private void Index(File dir){
		File[] files = dir.listFiles();
		for (int index = 0; index < files.length; index++){
			if(files[index].isFile()){
				if(DTA==null){
					DTA=main.menu.search.getDataTagsAdapter();
				}
				DTA.addFile(files[index]);
			}
			if(files[index].isDirectory()){
				Index(files[index]);
			}
		}
	}
	/**
	 * Returns list of all the sources currently being listened to
	 */
	public List<String> getSources() {
		String qSt=
			"SELECT t "+
			"FROM  sourcesdef t";
		SessionFactory sessionQFactory = SFac.get();
		if(sessionQFactory!=null)
		{
			System.out.println("sessionFactory  work");
		}
		Session session = sessionQFactory.openSession();
		if(session!=null){
			System.out.println("session work");
		}
		Query q=session.createQuery(qSt);
		List<sourcesdef> myTags=q.list();
		session.flush();
		int size=myTags.size();
		String tagsSt[]=new String[size];
		int j=0;
		for (sourcesdef element : myTags) // or sArray
		{
			tagsSt[j]=element.getPath();
			j++;
		}
		List<String> Tags = Arrays.asList(tagsSt);
		return Tags;
	}

	/**
	 *Change the name of existing source 
	 */
	public void setSource(String from, String to,String[] exp) {
		deleteSource(from);
		insertSource(to,exp);
		
	}



}
